package com.zyht.common.util;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * <b>描述：</b> 线程池<br/>
 * <b>作者：</b>Bob <br/>
 * <b>修改日期：</b>2016年8月23日 - 上午10:36:11<br/>
 */
public final class ThreadPoolUtils {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private ThreadPoolTaskExecutor threadPoolTaskExecutor;

	private ThreadPoolExecutor executor;

	private int threadpoolSize = 80;

	public class ThreadPool {

		ThreadPool(){

			if(null == threadPoolTaskExecutor){
				executor = new ThreadPoolExecutor(threadpoolSize,92,60,TimeUnit.SECONDS,
					new ArrayBlockingQueue<Runnable>(80),
					new ThreadPoolExecutor.DiscardOldestPolicy());
			}
		}

		public void putThread(Runnable run){

			if(null == threadPoolTaskExecutor){
				executor.execute(run);
				threadPoolTaskExecutor.execute(run);
				if(logger.isDebugEnabled()){
					logger.debug("The new thread has been put to pool<executor>......");
				}
			} else{
				threadPoolTaskExecutor.execute(run);
				if(logger.isDebugEnabled()){
					logger
						.debug("The new thread has been put to pool<threadPoolTaskExecutor>......");
				}
			}
		}
	}

	private static ThreadPool theadPool;

	public void init(){

		theadPool = new ThreadPool();
	}

	public static ThreadPool getUtils(){

		return theadPool;
	}

	public void setThreadPoolTaskExecutor(ThreadPoolTaskExecutor threadPoolTaskExecutor){

		this.threadPoolTaskExecutor = threadPoolTaskExecutor;
		if(logger.isInfoEnabled()){
			logger.info("The threadpool threadPoolTaskExecutor has been setten......");
		}
	}

	public void setThreadpoolSize(int threadpoolSize){

		this.threadpoolSize = threadpoolSize;
	}
}
